package com.bluesmart.mia;

import java.util.Timer;
import java.util.TimerTask;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.sys.DemoApp;
import com.umeng.message.UmengRegistrar;
import com.util.Constant;
import com.util.ImageLoaderHelper;
import com.util.MgqDataHandler;
import com.util.MgqRestClient;
import com.util.PreferencesUtils;
import com.util.ToastUtil;
import com.widget.CircleImageView;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainPageActivity extends FragmentActivity implements OnClickListener{
    private int mShowView = 2;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main_page);
		((TextView)findViewById(R.id.center)).setText(getString(R.string.feed));
		
        initRightMenu();
        sendGetBabyRequest();
        
        findViewById(R.id.icon).setOnClickListener(this);
        findViewById(R.id.left).setOnClickListener(this);
        findViewById(R.id.right).setOnClickListener(this);
        findViewById(R.id.left_s).setOnClickListener(this);
        findViewById(R.id.baby0).setOnClickListener(this);
        findViewById(R.id.baby1).setOnClickListener(this);
        findViewById(R.id.baby2).setOnClickListener(this);
        
        ((DemoApp) getApplicationContext()).addActivity(this);
	}
	
	@Override
	protected void onDestroy() {
		((DemoApp) getApplicationContext()).removeActivity(this);
		super.onDestroy();
	}
	
	public void sendGetBabyRequest() {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				aotuLogin();
				((DemoApp)getApplicationContext()).mBabyList = JSON.parseArray(response);

				if(((DemoApp)getApplicationContext()).mBabyList != null)
				{
					int count = ((DemoApp)getApplicationContext()).mBabyList.size();
					for(int i = 0; i < count; i++)
					{
						JSONObject item = ((DemoApp)getApplicationContext()).mBabyList.getJSONObject(i);
						if(item.getString("isCurr").equals("true")) ((DemoApp)getApplicationContext()).mSelectedBaby = i;
					}
					
					JSONObject obj = ((DemoApp)getApplicationContext()).getSeletedBaby();
					if(obj != null)
					{
						TextView tv = (TextView)slidingMenu.findViewById(R.id.btn10);
						tv.setTag(obj.toString());

						ImageLoaderHelper.displayImage(R.drawable.a53, (CircleImageView)findViewById(R.id.icon), 
								obj.getString("image"));
					}
				}
				
				sendHttpRequest();
			}
		};
		
		JSONObject params = new JSONObject();
		params.put("mia_un", PreferencesUtils.getString(this, "username"));
		params.put("pwd", PreferencesUtils.getString(this, "password"));
		params.put("handType", "get");

		MgqRestClient.postBody(Constant.SERVER_URL + "/sw/babyInfoHandler.ashx", JSON.toJSONString(params), loginHandler);
	}
	
	SlidingMenu slidingMenu = null;
	void initRightMenu()
	{
		OnClickListener listener = new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				menuBtn(arg0);
			}
		};
		
		slidingMenu = new SlidingMenu(this);
		slidingMenu.setMode(SlidingMenu.RIGHT);
		slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
		slidingMenu.setShadowDrawable(R.drawable.shadow);
		slidingMenu.setShadowWidthRes(R.dimen.shadow_width);
		slidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		slidingMenu.setMenu(R.layout.right_menu);
		slidingMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
		slidingMenu.setSecondaryShadowDrawable(R.drawable.shadow);
		slidingMenu.setFadeDegree(0.35f);
		
		slidingMenu.findViewById(R.id.btn4).setOnClickListener(listener);
		slidingMenu.findViewById(R.id.btn5).setOnClickListener(listener);
		slidingMenu.findViewById(R.id.btn6).setOnClickListener(listener);
		slidingMenu.findViewById(R.id.btn7).setOnClickListener(listener);
		slidingMenu.findViewById(R.id.btn8).setOnClickListener(listener);
		slidingMenu.findViewById(R.id.btn9).setOnClickListener(listener);
		slidingMenu.findViewById(R.id.btn10).setOnClickListener(listener);
		slidingMenu.findViewById(R.id.btn11).setOnClickListener(listener);
		slidingMenu.findViewById(R.id.btn12).setOnClickListener(listener);
		slidingMenu.findViewById(R.id.btn13).setOnClickListener(listener);
		slidingMenu.findViewById(R.id.btn14).setOnClickListener(listener);
		slidingMenu.findViewById(R.id.btn15).setOnClickListener(listener);
		slidingMenu.findViewById(R.id.btn16).setOnClickListener(listener);
	}
	
	private void sendHttpRequest() {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				
				JSONObject json = JSON.parseObject(response);
				if(json.keySet().size() > 0)
				{
					slidingMenu.findViewById(R.id.btn10).setVisibility(View.VISIBLE);
					((TextView)slidingMenu.findViewById(R.id.btn10)).setText(json.getString("deviceName"));
					((TextView)slidingMenu.findViewById(R.id.btn9)).setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
					slidingMenu.findViewById(R.id.btn9).setOnClickListener(null);
				}
			}
		};
		
		JSONObject obj = ((DemoApp)getApplicationContext()).getSeletedBaby();
		if(obj == null) return;
		
		JSONObject params = new JSONObject();
		params.put("mia_un", PreferencesUtils.getString(this, "username"));
		params.put("pwd", PreferencesUtils.getString(this, "password"));
		params.put("babyid", (((DemoApp)getApplicationContext()).getSeletedBaby().getString("babyid")));

		MgqRestClient.postBody(Constant.SERVER_URL + "/sw/DownLoadDeviceInfo.ashx", JSON.toJSONString(params), loginHandler);
	}
	
	protected void onResume()
	{
		super.onResume();
		setUserImage();

		if(((DemoApp)getApplicationContext()).isNewMsg)
		{
			((TextView)slidingMenu.findViewById(R.id.btn5)).setCompoundDrawablesWithIntrinsicBounds(
					R.drawable.bg_news, 0, R.drawable.a17, 0);
			((ImageButton)findViewById(R.id.right)).setImageResource(R.drawable.unread);
		}
		else
		{
			((TextView)slidingMenu.findViewById(R.id.btn5)).setCompoundDrawablesWithIntrinsicBounds(
					0, 0, R.drawable.a17, 0);
			((ImageButton)findViewById(R.id.right)).setImageResource(R.drawable.a25);
		}
		
        ((DashboardActivity)findViewById(R.id.view2)).sendHttpRequest(false);
	}
	
	public void setCenterTitle()
	{
	}
	
	void setUserImage()
	{
		if(((DemoApp)getApplicationContext()).mBabyList != null)
		{
			JSONObject obj = ((DemoApp)getApplicationContext()).getSeletedBaby();
			if(obj != null)
			{
				TextView tv = (TextView)slidingMenu.findViewById(R.id.btn10);
				tv.setTag(obj.toString());
				
				if(mShowView == 0)
				{
					findViewById(R.id.icon).setVisibility(View.INVISIBLE);
					findViewById(R.id.left).setVisibility(View.VISIBLE);
				}
				else if(mShowView == 3)
				{
				}
				else
				{
					findViewById(R.id.icon).setVisibility(View.VISIBLE);
					findViewById(R.id.left).setVisibility(View.INVISIBLE);
					findViewById(R.id.command).setVisibility(View.INVISIBLE);
				
					ImageLoaderHelper.displayImage(R.drawable.a53, (CircleImageView)findViewById(R.id.icon), 
							obj.getString("image"));
				}
			}
		}
		
		if(mShowView == 0)
		{
			findViewById(R.id.icon).setVisibility(View.INVISIBLE);
			findViewById(R.id.left).setVisibility(View.VISIBLE);
		}
		else
		{
			findViewById(R.id.icon).setVisibility(View.VISIBLE);
			findViewById(R.id.left).setVisibility(View.INVISIBLE);
			findViewById(R.id.command).setVisibility(View.INVISIBLE);
		}
	}
	
	Handler handle = new Handler(){
		public void handleMessage(Message msg)
		{
			switch(msg.what)
			{
			case R.id.btn0:
	            ((DashboardActivity)findViewById(R.id.view2)).sendHttpRequest(false);
				break;
			
			case R.id.btn2:
	            ((ScheduleActivity)findViewById(R.id.view1)).sendHttpRequest(false);
				break;
//			
//			case R.id.btn3:
//	            ((BabyActivity)findViewById(R.id.view0)).sendChartHttpRequest(false);
//				break;
			}
		}
	};
	
	public void intoWeek(int index,int week)
	{
		changeView(index);
	}
	
	public void changeView(final int index)
	{
		if((index == R.id.btn3 && mShowView == 0)
				|| (index == R.id.btn2 && mShowView == 1)
				|| (index == R.id.btn0 && mShowView == 2)
				|| (index == R.id.btn1 && mShowView == 3))
		{
			return;
		}
		
		switch(index)
		{
		case R.id.btn2:
		{
			if(mShowView == 0)
			{
				Animation anim = AnimationUtils.loadAnimation(MainPageActivity.this, R.anim.slide_in_from_bottom); 
				findViewById(R.id.view1).startAnimation(anim);  
	            findViewById(R.id.view1).setVisibility(View.VISIBLE);
			}
			else
			{
	            findViewById(R.id.view1).setVisibility(View.VISIBLE);
	            Animation anim = AnimationUtils.loadAnimation(MainPageActivity.this, R.anim.slide_out_to_bottom);  
	            findViewById(R.id.view0 + mShowView).startAnimation(anim);  
	            findViewById(R.id.view0 + mShowView).setVisibility(View.INVISIBLE);
			}
			
            findViewById(R.id.view2).setVisibility(View.INVISIBLE);
			mShowView = 1;
			break;
		}
		
		case R.id.btn0:
		{
			if(mShowView < 2)
			{
				Animation anim = AnimationUtils.loadAnimation(MainPageActivity.this, R.anim.slide_in_from_bottom); 
				findViewById(R.id.view2).startAnimation(anim);  
	            findViewById(R.id.view2).setVisibility(View.VISIBLE);
			}
			else
			{
	            findViewById(R.id.view2).setVisibility(View.VISIBLE);
	            Animation anim = AnimationUtils.loadAnimation(MainPageActivity.this, R.anim.slide_out_to_bottom);  
	            findViewById(R.id.view0 + mShowView).startAnimation(anim);  
	            findViewById(R.id.view0 + mShowView).setVisibility(View.INVISIBLE);
			}

			mShowView = 2;
			break;
		}
		
		case R.id.btn1:
		{
			break;
		}
		
		case R.id.btn3:
			startActivity(new Intent(this,BabyListActivity.class));
			return;
		}
		
		new Timer().schedule(new TimerTask(){
			@Override
			public void run() {
				handle.sendEmptyMessage(index);
			}
		}, 1100);
		
		setUserImage();
	}
	
	void menuBtn(View arg0)
	{
		slidingMenu.toggle(false);
		
		switch(arg0.getId())
		{
		case R.id.btn0:
		case R.id.btn1:
		case R.id.btn2:
//		case R.id.btn3:
			changeView(arg0.getId());
			break;

		case R.id.btn5:
			startActivity(new Intent(this,NotificationActivity.class));
			break;

		case R.id.btn6:
			startActivity(new Intent(this,GeneralActivity.class));
			break;
			
		case R.id.btn4:
			startActivity(new Intent(this,AccountActivity.class));
			break;
			
		case R.id.btn9:
			startActivity(new Intent(this,AddDeviceActivity.class));
			break;
			
		case R.id.btn10:
		case R.id.btn11:
		case R.id.btn12:
		case R.id.btn13:
		case R.id.btn14:
		case R.id.btn15:
		case R.id.btn16:
		{
			Intent intent = new Intent(this,DeviceInfoActivity.class);
			intent.putExtra("obj", (String)arg0.getTag());
			startActivity(intent);
			break;
		}
		}
	}
	
	private void aotuLogin() {
		MgqDataHandler loginHandler = new MgqDataHandler(this, false, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);

				if (ruser.getString("resCode").equals("1000")) {
					PreferencesUtils.putString(getApplicationContext(), "nickname", ruser.getString("nickname"));
					PreferencesUtils.putString(getApplicationContext(), "userimg", ruser.getString("userimg"));
					PreferencesUtils.putString(getApplicationContext(), "accessToken", ruser.getString("accessToken"));
				}
				else if (ruser.getString("resCode").equals("2000")) {
					ToastUtil.showToastWithAlertPic(R.string.error_2000);
				}
				else if (ruser.getString("resCode").equals("3000")) {
					ToastUtil.showToastWithAlertPic(R.string.error_3000);
				}
				else 
				{
				}
			}
		};
		
		JSONObject params = new JSONObject();
		params.put("userName", PreferencesUtils.getString(this, "username"));
		params.put("pwd", PreferencesUtils.getString(this, "password"));
		params.put("tid", "");
		params.put("deviceid", UmengRegistrar.getRegistrationId(this));

		MgqRestClient.postBody(Constant.SERVER_URL + "/sw/login.ashx", JSON.toJSONString(params), loginHandler);
	}
	
	@Override
	public void onBackPressed() {
		exitApp();
	}

	private long exitTime = 0;
	public void exitApp() {
		if ((System.currentTimeMillis() - exitTime) > 2000) {
			Toast.makeText(this, "再按一次退出", Toast.LENGTH_LONG).show();
			exitTime = System.currentTimeMillis();
		} else {
			this.finish();
		}
	}
	
	@Override
	public void onClick(View arg0) {
		switch(arg0.getId())
		{
		case R.id.icon:
			startActivity(new Intent(this,BabyViewActivity.class));
			break;
			
		case R.id.left:
			findViewById(R.id.command).setVisibility(View.VISIBLE);
			break;
		
		case R.id.right:
			slidingMenu.toggle(true);
			break;
			
		case R.id.left_s:
			findViewById(R.id.command).setVisibility(View.INVISIBLE);
			break;
			
		case R.id.baby1:
			startActivity(new Intent(this,BabyProfileActivity.class));
			findViewById(R.id.command).setVisibility(View.INVISIBLE);
			break;
			
		case R.id.baby2:
			startActivity(new Intent(this,BabyCaregiversActivity.class));
			findViewById(R.id.command).setVisibility(View.INVISIBLE);
			break;

		case R.id.baby0:
			startActivity(new Intent(this,BabyProfileEditActivity.class));
			findViewById(R.id.command).setVisibility(View.INVISIBLE);
			break;
	}
	}
	
	public void showShedule()
	{
		Animation anim = AnimationUtils.loadAnimation(MainPageActivity.this, R.anim.slide_in_from_top);  
        findViewById(R.id.view1).startAnimation(anim);  
        findViewById(R.id.view1).setVisibility(View.VISIBLE);
		mShowView = 1;
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data == null)
			return;
		
		((BabyActivity)findViewById(R.id.view0)).onActivityResult(requestCode, resultCode, data);
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	public void startActivityForBaby(int index)
	{
		switch(index)
		{
		case 0:
			startActivityForResult(new Intent(this,AddProfileWeightActivity.class), 10);
			break;
			
		case 1:
			startActivityForResult(new Intent(this,AddProfileHeightActivity.class), 11);
			break;
			
		case 2:
			Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
			getAlbum.setType("image/*");
			startActivityForResult(getAlbum, 3);
			break;
			
		case 3:
			startActivityForResult(new Intent("android.media.action.IMAGE_CAPTURE"), 4);
			break;
		}
	}
}
